package org.blankhole.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * spring框架上下文工具类：
 * 		1.提供在非spring类中获取spring上下文:通过实现ApplicationContextAware获取ApplicationContext
 * 		2.通过BeanFactoryUtils.beanOfType从spring容器中获取对应类
 * note: 需要在配置文件中添加配置，如 
 * 		 <bean id="SpringContextUtils" class="org.blankhole.util.SpringContextUtils"></bean>
 * 
 * @author Wenlong Meng(wenlong.meng@gmail.com)
 * @version 1.0 at 2011/09/06
 * @since 1.0
 */
public class SpringContextUtils implements ApplicationContextAware {
	
	//local variables
	/**
	 * 上下文
	 */
	private static ApplicationContext context;

	//Logic
	/**
	 * 获取上下文
	 * 
	 * @return
	 */
	public static ApplicationContext getContext(){
		return context;
	}
	
	/**
	 * 获取spring中type类对应的实例对象
	 *  
	 * @param type
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T> T beanOfType(Class<?> type){
		return (T)BeanFactoryUtils.beanOfType(context, type);
	}

	
	/**
	 * 启动时，通过spring容器自动调用该方法，传递上下文
	 * 
	 * @param applicationContext 上下文
	 * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		context = applicationContext;
	}
	
	/**
	 * build ApplicationContext for spring
	 * 
	 * @return
	 */
	public static ApplicationContext buildApplicationContext(){
		return new ClassPathXmlApplicationContext(new String[]{"classpath:*.xml"});
	}

}
